package com.cneport.das.server.trans.core;

import com.cneport.das.common.security.pub.DefaultKeyStore;
import com.cneport.das.common.utils.DateUtil;
import com.cneport.das.common.utils.SecurityUtils;
import com.cneport.das.common.utils.StringUtil;
import com.cneport.das.server.conf.ConfigCaches;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Locale;

/**
 * @Desc 秘钥对的生成或获取的方法
 * @Ver 1.0
 * @Author GavinZhang
 * @Company 东方物通科技有限（北京）公司
 * @Date 2022-01-07 10:35:36
 */
@Service
public class SecurityKeyService {

    @Autowired
    private ConfigCaches configCaches;

    /**
     * 生成秘钥对
     * 秘钥的名称格式：COP00001_1.0_PUB.pem(公钥),COP00001_1.0_PRI.pem(公钥)
     *
     * @param path     秘钥对的存放更目录
     * @param certName 秘钥名称（名称的一部分，常常为公司编号）
     * @param version  版本
     * @return
     */
    public String genEncryptKey(String path, String certName, String version) {
        if (StringUtil.isBlank(certName)) {
            certName = DateUtil.C8() + ".1";
        }
        if (StringUtil.isBlank(version)) {
            version = "1.0";
        }
        try {
            KeyPair keyPair = SecurityUtils.generateKey("RSA", 2048);
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();

            String parentDir = path;
            File file = new File(parentDir);
            if (!file.exists()) {
                file.mkdirs();
            }

            String fullCertName = certName + "_" + version + "_";

            String priKey = parentDir + File.separator + fullCertName + "PRI";

            String pubKey = parentDir + File.separator + fullCertName + "PUB";

            File file1 = new File(priKey + ".pem");
            FileOutputStream fo1 = new FileOutputStream(file1);
            DefaultKeyStore defaultKeyStore = new DefaultKeyStore(privateKey, null);
            defaultKeyStore.saveKeyAsPEM(fo1);

            File file2 = new File(pubKey + ".pem");
            FileOutputStream fo2 = new FileOutputStream(file2);
            defaultKeyStore = new DefaultKeyStore(null, publicKey);
            defaultKeyStore.saveKeyAsPEM(fo2);
            StringBuilder sb = new StringBuilder();
            sb.append("密钥对已经成功生成：\t\n");
            sb.append("私钥：" + priKey + "\t\n");
            sb.append("公钥：" + pubKey + "\t\n");
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "密钥对生成失败！";
    }

    /**
     * s
     * 根据输入 生成 秘钥对
     *
     * @param path
     * @param corpNo
     * @return
     */
    public String genEncryptKeyWithCorpNo(String path, String corpNo) {
        return genEncryptKey(path, corpNo, null);
    }

    /**
     * 获取秘钥的绝对路径,没有指定 keyType,默认返回公钥文件名
     *
     * @param corp    公司编号或一个C10+".1"的字符串
     * @param enctVer 版本
     * @param keyType 类型：pri或pub
     * @return
     */
    public String getKeyFilePath(String corp, String enctVer, String keyType) {
        final String pem = "pem";
        if (StringUtil.isBlank(enctVer)) {
            enctVer = "1.0";
        }
        String path = "";
        if (keyType != null && keyType.toLowerCase(Locale.ROOT).equals("pri")) {
            path = corp + "_" + enctVer + "_PRI.pem";
        } else {
            path = corp + "_" + enctVer + "_PUB.pem";
        }
        String dir = configCaches.getConfBasePath() + File.separator + corp + File.separator + pem + File.separator;
        return dir + path;
    }

}
